package com.es.controller;

import com.google.common.primitives.Longs;
import com.qiniu.util.StringUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lizhenzhong
 * @date 2019/5/6
 */
@RestController
public class EsTestController {
    private Logger logger  = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TransportClient transportClient;

    /**
     * test
     * @return
     */
    @RequestMapping(value = "/test")
    public String test(){
        GetResponse response = transportClient.prepareGet("lib3","user","1").execute().actionGet();
        return response.getSourceAsString();
    }

    /**
     * 查询
     * @param keyword
     * @param name
     * @param startAge
     * @param endAge
     * @return
     */
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public String query(@RequestParam(name = "keyword") String keyword,@RequestParam(name = "name") String name,@RequestParam(name = "startAge") int startAge,@RequestParam(name = "endAge") int endAge){
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //单个匹配姓名
        if(!StringUtils.isNullOrEmpty(name)) {
            boolQuery.filter(QueryBuilders.termQuery("name", keyword));
        }
        //年龄匹配
        if (startAge > 0 || endAge > 0) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
            if (endAge > 0) {
                rangeQueryBuilder.lte(endAge);
            }
            if (startAge > 0) {
                rangeQueryBuilder.gte(startAge);
            }
            boolQuery.filter(rangeQueryBuilder);
        }
        //关键词多个匹配
        if(!StringUtils.isNullOrEmpty(keyword)) {
            boolQuery.must(QueryBuilders.multiMatchQuery(keyword, "address", "name", "interests"));
        }
        SearchRequestBuilder requestBuilder = this.transportClient.prepareSearch("lib4")
                .setTypes("user")
                .setQuery(boolQuery)
                .addSort("age", SortOrder.fromString("desc"))
                .setFrom(0)
                .setSize(10)
                .setFetchSource("name", null);
        logger.debug(requestBuilder.toString());

        SearchResponse response = requestBuilder.get();
        if (response.status() != RestStatus.OK) {
            logger.warn("Search status is no ok for " + requestBuilder);
            return "查询失败";
        }

        List<String> strList = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            System.out.println(hit.getSource());
            strList.add(hit.getSource().get("name").toString());
        }
        return strList.stream().collect(Collectors.joining(","));
    }
}
